package com.ruoyi.web.controller.system;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Calendar;
import javax.servlet.http.HttpServletResponse;

import com.ruoyi.common.core.domain.entity.SysUser;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.PutMapping;
import org.springframework.web.bind.annotation.DeleteMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import com.ruoyi.common.annotation.Log;
import com.ruoyi.common.core.controller.BaseController;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.enums.BusinessType;
import com.ruoyi.system.domain.DevelopmentTop;
import com.ruoyi.system.service.IDevelopmentTopService;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.common.core.page.TableDataInfo;
import org.springframework.web.multipart.MultipartFile;

/**
 * 发展量排名Controller
 * 
 * @author ruoyi
 * @date 2025-08-05
 */
@RestController
@RequestMapping("/system/top")
public class DevelopmentTopController extends BaseController
{
    @Autowired
    private IDevelopmentTopService developmentTopService;

    /**
     * 查询发展量排名列表
     */
    @PreAuthorize("@ss.hasPermi('system:top:list')")
    @GetMapping("/list")
    public TableDataInfo list(DevelopmentTop developmentTop)
    {
        startPage();
        List<DevelopmentTop> list = developmentTopService.selectDevelopmentTopList(developmentTop);
        return getDataTable(list);
    }

    /**
     * 导出发展量排名列表
     */
    @PreAuthorize("@ss.hasPermi('system:top:export')")
    @Log(title = "发展量排名", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, DevelopmentTop developmentTop)
    {
        List<DevelopmentTop> list = developmentTopService.selectDevelopmentTopList(developmentTop);
        ExcelUtil<DevelopmentTop> util = new ExcelUtil<DevelopmentTop>(DevelopmentTop.class);
        util.exportExcel(response, list, "发展量排名数据");
    }

    /**
     * 获取发展量排名详细信息
     */
    @PreAuthorize("@ss.hasPermi('system:top:query')")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return success(developmentTopService.selectDevelopmentTopById(id));
    }

    /**
     * 新增发展量排名
     */
    @PreAuthorize("@ss.hasPermi('system:top:add')")
    @Log(title = "发展量排名", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody DevelopmentTop developmentTop)
    {
        return toAjax(developmentTopService.insertDevelopmentTop(developmentTop));
    }

    /**
     * 修改发展量排名
     */
    @PreAuthorize("@ss.hasPermi('system:top:edit')")
    @Log(title = "发展量排名", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody DevelopmentTop developmentTop)
    {
        return toAjax(developmentTopService.updateDevelopmentTop(developmentTop));
    }

    /**
     * 删除发展量排名
     */
    @PreAuthorize("@ss.hasPermi('system:top:remove')")
    @Log(title = "发展量排名", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(developmentTopService.deleteDevelopmentTopByIds(ids));
    }

    @Log(title = "发展量导入", businessType = BusinessType.IMPORT)
    @PreAuthorize("@ss.hasPermi('system:user:import')")
    @PostMapping("/importData")
    public AjaxResult importData(MultipartFile file, boolean updateSupport) throws Exception
    {
        ExcelUtil<DevelopmentTop> util = new ExcelUtil<DevelopmentTop>(DevelopmentTop.class);
        List<DevelopmentTop> developmentTopList = util.importExcel(file.getInputStream());
        String operName = getUsername();
        String message = developmentTopService.importDevelopmentTop(developmentTopList, updateSupport, operName);
        return success(message);
    }

    @PostMapping("/importTemplate")
    public void importTemplate(HttpServletResponse response)
    {
        ExcelUtil<DevelopmentTop> util = new ExcelUtil<DevelopmentTop>(DevelopmentTop.class);
        util.importTemplateExcel(response, "实时发展量");
    }

    @PostMapping("/getTotal")
    public AjaxResult getTotal(@RequestBody DevelopmentTop developmentTop)
    {
        List<DevelopmentTop> total = developmentTopService.getTotal(developmentTop);
        return success(total);
    }

    @GetMapping("/getAllBusinessDepartmentTotals")
    public AjaxResult getAllBusinessDepartmentTotals(@RequestParam(defaultValue = "true") boolean descending, Long deptId, Date targetTime)
    {
        // 如果传入了日期时间，转换为只包含年月日的格式

        
        List<DevelopmentTop> totals = developmentTopService.getAllBusinessDepartmentTotals(descending, deptId, targetTime);
        List<DevelopmentTop> selfDept = new ArrayList<>();
        Map<String, Object> map = new HashMap<>();
        
        if (descending) {
            // 当descending为true时，保持原有逻辑
            for (DevelopmentTop developmentTop : totals) {
                if (developmentTop.getDeptId().equals(deptId)) {
                    selfDept.add(developmentTop);
                }
            }
            map.put("selfDept", selfDept);
            map.put("totals", totals);
        } else {
            // 当descending为false时，拆分成两个list
            List<DevelopmentTop> zeroList = new ArrayList<>();
            List<DevelopmentTop> nonZeroList = new ArrayList<>();
            
            // 分离fttr+全量融合为0和非0的数据
            for (DevelopmentTop total : totals) {
                int fttrValue = parseIntSafe(total.getFttr());
                int fullFusionValue = parseIntSafe(total.getFullFusion());
                int sum = fttrValue + fullFusionValue;
                
                if (sum == 0) {
                    zeroList.add(total);
                } else {
                    nonZeroList.add(total);
                }
                
                // 同时检查是否为当前部门
                if (total.getDeptId().equals(deptId)) {
                    selfDept.add(total);
                }
            }
            
            map.put("selfDept", selfDept);
            map.put("zeroList", zeroList);
            map.put("nonZeroList", nonZeroList);
        }
        
        return success(map);
    }
    
    /**
     * 查询指定四个小区的实时发展量和目标值
     * @param targetTime 目标时间
     * @return 四个小区的详细数据列表
     */
    @GetMapping("/getSpecificCommunitiesData")
    public AjaxResult getSpecificCommunitiesData(@RequestParam String targetTime) {
        try {
            List<Map<String, Object>> resultList = developmentTopService.getSpecificCommunitiesData(targetTime);
            return success(resultList);
        } catch (Exception e) {
            return error("查询失败: " + e.getMessage());
        }
    }
    
    private int parseIntSafe(String s) {
        try {
            if (s == null || s.trim().isEmpty()) return 0;
            return Integer.parseInt(s.trim());
        } catch (Exception e) {
            return 0;
        }
    }

    /**
     * 查询四个小区的各项套餐总和以及目标总和
     *
     * @param targetTime 活动日期
     * @return 包含套餐总和与目标总和的Map
     */
    @GetMapping("/getFourCommunitiesPackageSums")
    public AjaxResult getFourCommunitiesPackageSums(@RequestParam String targetTime) {
        try {
            Map<String, Object> result = developmentTopService.getFourCommunitiesPackageSums(targetTime);
            return success(result);
        } catch (Exception e) {
            return error("查询四个小区的各项套餐总和失败: " + e.getMessage());
        }
    }

    /**
     * 根据部门ID和目标时间查询该部门下每个人的套餐具体办理流程
     *
     * @param deptId 部门ID
     * @param targetTime 目标时间
     * @return 每个人的套餐办理详情列表
     */
    @GetMapping("/getSalesmanPackageDetails")
    public AjaxResult getSalesmanPackageDetails(@RequestParam Long deptId, @RequestParam String targetTime) {
        try {
            List<Map<String, Object>> resultList = developmentTopService.getSalesmanPackageDetails(deptId, targetTime);
            return success(resultList);
        } catch (Exception e) {
            return error("查询个人套餐办理详情失败: " + e.getMessage());
        }
    }
}
